package com.orhon.smartcampus.modules.base.mutation;

import com.alibaba.fastjson.JSON;
import com.orhon.smartcampus.basicComponents.Result;
import com.orhon.smartcampus.modules.base.dao.PeriodsDao;
import com.orhon.smartcampus.modules.base.entity.Periods;
import com.orhon.smartcampus.modules.base.gqlInputModel.GQLPeriodInput;
import com.orhon.smartcampus.modules.base.inputMapper.PeriodInputMapper;
import graphql.schema.DataFetcher;
import graphql.schema.DataFetchingEnvironment;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.Date;

@Component
public class AddPeriodMutation implements DataFetcher {


    @Autowired
    PeriodsDao periodsDao;

    /**
     * 新增/修改学段信息
     * editor : ths
     */
    @Override
    public Object get(DataFetchingEnvironment environment) throws Exception {

        GQLPeriodInput input = PeriodInputMapper.MAPPER.mapInput2(environment.getArgument("inputData"));

        Periods periods = null;

        if (input.getId() != null) {
            periods = periodsDao.get(Periods.class, input.getId());
            periods.setUpdatedAt(new Date());
        } else {
            periods = new Periods();
            periods.setCreatedAt(new Date());
        }
        if(input.getPeriod_name() != null){

            periods.setPeriodName(JSON.toJSONString(input.getPeriod_name()));
        }
        if(input.getMark() != null){

            periods.setMark(input.getMark());
        }
        if(input.getPeriod_slug() != null){

            periods.setPeriodSlug(input.getPeriod_slug());
        }
        if(input.getPeriod_number() != null){

            periods.setPeriodNumber(input.getPeriod_number());
        }
        if(input.getPeriod_order() != null){

            periods.setPeriodOrder(input.getPeriod_order());
        }
        try {
            periodsDao.saveOrUpdate(periods);
        } catch (Exception e) {
            return Result.error(500, "" + e);
        }

        return Result.ok();
    }

}

